#include "widget.h"
#include "ui_widget.h"

MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
    ui->teLog->setReadOnly(true);
    ui->le_fileName->setReadOnly(true);
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::on_pb_browse_clicked()
{
    fileName_ = QFileDialog::getOpenFileName(this,tr("Open File"),"/home","ALL(*);; Ecnryptedfiles[.enc](*.enc)");
    ui->le_fileName->setText(fileName_);
}

void MainWidget::on_pb_encrypt_clicked()
{
    QString password;
    pwddialog pwd(this);
    pwd.exec();
    password = pwd.getPassword();

    //basic validation
    if(password.isEmpty()){
        ui->teLog->append("Error: Password cannot be empty");;
        return;
    }

    //do the encryption
    AES_KEY* ekey = (AES_KEY*)malloc( sizeof(AES_KEY) );


//    if( AES_set_encrypt_key((const unsigned char*)password.toLatin1().data(),256,ekey) != 0 )
//        printf("Error , Generating the Encrypted Key\n");

      if( AES_set_encrypt_key((const unsigned char*)password.toLatin1().data(),128,ekey) != 0 )
          printf("Error , Generating the Encrypted Key\n");

    QString encryptedFilename = fileName_;
    encryptedFilename.append(".enc");
    encryptFile((unsigned char*)fileName_.toLatin1().data(),(unsigned char*)encryptedFilename.toLatin1().data(),ekey);

}

void MainWidget::on_pb_decrypt_clicked()
{
    QString password;
    pwddialog pwd(this);
    pwd.exec();
    password = pwd.getPassword();

    //basic validation
    if(password.isEmpty()){
        ui->teLog->append("Error: Password cannot be empty");;
        return;
    }

    AES_KEY* dkey = (AES_KEY*)malloc( sizeof(AES_KEY) );


    if( AES_set_decrypt_key((unsigned const char*)password.toLatin1().data(),128,dkey) != 0 )
        printf("Error , Generating the decrypted Key\n");
\
    QString encryptedFilename = fileName_;

    if(!fileName_.contains("enc"))
    {
        ui->teLog->append("Error: Please select a valid file with .enc extension, which was previously encrypted by this program");
        return;

    }

    QString decryptedFilename = fileName_.remove(".enc");

    ui->teLog->append("\n\nDecrypted Filename is ");
    ui->teLog->append(decryptedFilename);

    QString tempFileName = QFileInfo(decryptedFilename).fileName();
    QString tempFilePath = QFileInfo(decryptedFilename).filePath();

    tempFileName.prepend("_decryptd_");

    decryptedFilename = tempFilePath+tempFileName;


    ui->teLog->append("\n\nFile to be Decrypted");
    ui->teLog->append(encryptedFilename);
    qDebug()<<"Decryption Input Filenam "<<fileName_;

    ui->teLog->append("\n\nDecrypted Filename is ");
    ui->teLog->append(decryptedFilename);

    decryptFile((unsigned char*)encryptedFilename.toLatin1().data(),(unsigned char*)decryptedFilename.toLatin1().data(),dkey);


}
